
package com.eworking.eim.group;

import org.jivesoftware.smack.Connection;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smackx.muc.InvitationListener;
import org.jivesoftware.smackx.muc.MultiUserChat;
import org.jivesoftware.smackx.muc.RoomInfo;

import com.eworking.eim.EIMManager;
import com.eworking.eim.user.EIMAccountUtils;

public class EIMInvitationListener implements InvitationListener {
    
    @Override
    public void invitationReceived(Connection connection, String roomJID, String inviter, String reason, String arg4,
        Message message) {
        String groupId = EIMAccountUtils.getGroupIdFromGroupJID(roomJID);
        String inviterAccount = EIMAccountUtils.getAccountFromJID(inviter);
        String groupName = "";
        try {
            RoomInfo roomInfo = MultiUserChat.getRoomInfo(connection, roomJID);
            groupName = roomInfo.getRoom() == null ? groupId : roomInfo.getRoom();
            // 自动接受邀请
            if (EIMGroupManager.getInstance().autoAcceptInvitation) {
                // 接受邀请
                EIMGroupManager.getInstance().acceptInvitation(groupId);
            }
            // 应用是否已加载
            if (EIMManager.getInstance().isAppInited) {
                for (EIMGroupChangeListener groupChangeListener : EIMGroupManager.getInstance().allGroupChangeListeners) {
                    // 界面UI提示
                    groupChangeListener.onInvitationReceived(groupId, groupName, inviterAccount, reason);
                }
            }
        } catch (Exception e) {
            EIMGroupChangeEvent groupChangeEvent =
                new EIMGroupChangeEvent(EIMGroupChangeEvent.GroupEventType.Invitate, groupId, groupName, inviter,
                    reason);
            EIMGroupManager.getInstance().addGroupChangeEvent(groupChangeEvent);
        }
    }
}
